import express, { Request, Response, Router } from 'express';
import { MessageService } from '../models/Message';
import { PaginationResponse} from '../types/SharedTypes';
import { Op } from 'sequelize';

const router: Router = express.Router();
const messageService = new MessageService();

// 获取消息数据（按时间倒序分页）
router.get('/', async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 50,
      roomId,
      sessionId,
      userId,
      startDate,
      endDate,
      messageType
    } = req.query;

    const Message = (await import('../models/sequelize/Message')).default;

    // 构建查询条件
    const whereClause: any = {};

    if (roomId) {
      whereClause.roomId = roomId;
    }

    if (sessionId) {
      whereClause.sessionId = sessionId;
    }

    if (userId) {
      whereClause.userId = userId;
    }

     
    whereClause.messageType = messageType||"WebcastChatMessage";
     

    if (startDate || endDate) {
      whereClause.createdAt = {};
      if (startDate) {
        whereClause.createdAt[Op.gte] = new Date(startDate as string);
      }
      if (endDate) {
        whereClause.createdAt[Op.lte] = new Date(endDate as string);
      }
    }

    const pageNum = parseInt(page as string, 10);
    const pageSizeNum = parseInt(pageSize as string, 10);

    // 计算偏移量
    const offset = (pageNum - 1) * pageSizeNum;

    // 查询消息数据
    const messages = await Message.findAll({
      where: whereClause,
      order: [['createdAt', 'DESC']],
      limit: pageSizeNum,
      offset: offset,
      raw: false,
      include: [
        {
          model: (await import('../models/sequelize/Room')).default,
          as: 'room',
          attributes: ['id', 'title', 'coverUrl', 'streamerName', 'streamerAvatar', 'streamerDisplayId', 'streamerShortId', 'followCount', 'type', 'weight'],
          required: false,
        },
        {
          model: (await import('../models/sequelize/LiveSession')).default,
          as: 'session',
          attributes: ['id', 'startTime', 'endTime'],
          required: false,
        },
        {
          model: (await import('../models/sequelize/UserSnapshot')).default,
          as: 'userSnapshot',
          attributes: ['id', 'userName', 'userAvatar', 'payGrade', 'fansLevel', 'fansClubName'],
          required: false,
        },     
      ],
      // 添加子查询和复杂计算以进一步减慢查询
      subQuery: false,
      // 这个很重要，防止Sequelize将关联表中的数据压缩成嵌套对象，而是保留完整的数据行
      nest: false
    });

    // 转换数据格式（使用UserSnapshot关联数据）
    const messageItems = messages.map((msg: any) => ({
      id: msg.id,
      roomId: msg.roomId,
      userId: msg.userId,
      sessionId: msg.sessionId,
      userSnapshotId: msg.userSnapshotId,
      type: msg.messageType,
      content: msg.content,
      extraData: msg.extraData,
      // 从UserSnapshot关联中获取用户快照数据
      userName: msg.userSnapshot?.userName || null,
      userAvatar: msg.userSnapshot?.userAvatar || null,
      userGender: msg.userSnapshot?.userGender || null,
      payGrade: msg.userSnapshot?.payGrade || null,
      fansLevel: msg.userSnapshot?.fansLevel || null,
      fansClubName: msg.userSnapshot?.fansClubName || null,
      // 管理员权限字段
      isAdmin: msg.userSnapshot?.isAdmin || false,
      // 房间关联数据
      room: msg.room ? {
        id: msg.room.id,
        title: msg.room.title,
        streamerName: msg.room.streamerName,
        coverUrl: msg.room.coverUrl,
        streamerAvatar: msg.room.streamerAvatar,
      } : null,

      createdAt: msg.createdAt,
      dataType: 'message'
    }));

    // 获取总数
    const total = await Message.count({ 
      where: whereClause,
      distinct: true,
      include: [
        {
          model: (await import('../models/sequelize/Room')).default,
          as: 'room',
          required: false,
        },
        {
          model: (await import('../models/sequelize/LiveSession')).default,
          as: 'session',
          required: false,
        },
        {
          model: (await import('../models/sequelize/UserSnapshot')).default,
          as: 'userSnapshot',
          required: false,
        }
      ]
    });

    const pagination: PaginationResponse = {
      current: pageNum,
      pageSize: pageSizeNum,
      total: total,
      totalPages: Math.ceil(total / pageSizeNum)
    };

    const response = {
      success: true,
      data: messageItems,
      pagination
    };

    res.json(response);
  } catch (error) {
    console.error('获取消息数据失败:', error);
    res.status(500).json({ 
      success: false, 
      error: '获取消息数据失败' 
    });
    return;
  }
});

// 获取消息统计信息
router.get('/stats', async (req: Request, res: Response) => {
  try {
    const Message = (await import('../models/sequelize/Message')).default;
    const { Op } = await import('sequelize');
    
    // 获取今日消息数
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    const todayCount = await Message.count({
      where: {
        createdAt: {
          [Op.gte]: today,
          [Op.lt]: tomorrow
        }
      }
    });
    
    // 获取总消息数
    const totalCount = await Message.count();
    
    // 获取按消息类型统计
    const typeStats = await Message.findAll({
      attributes: ['messageType', [(await import('sequelize')).fn('COUNT', '*'), 'count']
      ],
      group: ['messageType'],
      raw: true
    });
    
    res.json({
      success: true,
      data: {
        todayCount,
        totalCount,
        typeStats
      }
    });
  } catch (error) {
    console.error('获取消息统计失败:', error);
    res.status(500).json({ error: '获取消息统计失败' });
  }
});

// 删除消息
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    const Message = (await import('../models/sequelize/Message')).default;
    const message = await Message.findByPk(id);
    
    if (!message) {
      res.status(404).json({ error: '消息不存在' });
      return;
    }
    
    await message.destroy();
    
    res.json({
      success: true,
      message: '消息删除成功'
    });
  } catch (error) {
    console.error('删除消息失败:', error);
    res.status(500).json({ error: '删除消息失败' });
  }
});

// 获取房间消息
router.get('/room/:roomId', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.params;
    const { limit = 100 } = req.query;
    
    const messages = await messageService.getRoomMessages(
      roomId, 
      parseInt(limit as string)
    );
    
    res.json({ 
      success: true, 
      data: messages,
      count: messages.length
    });
  } catch (error) {
    console.error('获取房间消息失败:', error);
    res.status(500).json({ error: '获取房间消息失败' });
  }
});

// 获取用户在房间的消息历史
router.get('/user/:userId/room/:roomId', async (req: Request, res: Response) => {
  try {
    const { userId, roomId } = req.params;
    const { limit = 50 } = req.query;
    
    const messages = await messageService.getUserMessages(
      userId,
      roomId,
      parseInt(limit as string)
    );
    
    res.json({ 
      success: true, 
      data: messages,
      count: messages.length
    });
  } catch (error) {
    console.error('获取用户消息失败:', error); 
    res.status(500).json({ error: '获取用户消息失败' }); 
  }
});

// 根据消息类型筛选房间消息
router.get('/room/:roomId/type/:messageType', async (req: Request, res: Response) => {
  try {
    const { roomId, messageType } = req.params;
    const { limit = 100 } = req.query;
    
    const Message = (await import('../models/sequelize/Message')).default;
    const messages = await Message.findAll({
      where: { 
        roomId,
        messageType
      },
      order: [['createdAt', 'DESC']],
      limit: parseInt(limit as string)
    });
    
    res.json({ 
      success: true, 
      data: messages,
      count: messages.length
    });
  } catch (error) {
    console.error('获取指定类型消息失败:', error);
    res.status(500).json({ error: '获取指定类型消息失败' });
  }
});

// 获取房间最新消息（实时查询）
router.get('/room/:roomId/latest', async (req: Request, res: Response) => {
  try {
    const { roomId } = req.params;
    const { since } = req.query; // 时间戳，获取此时间之后的消息
    
    const Message = (await import('../models/sequelize/Message')).default;
    const { Op } = await import('sequelize');
    const whereClause: any = { roomId };
    
    if (since) {
      whereClause.createdAt = {
        [Op.gt]: new Date(parseInt(since as string))
      };
    }
    
    const messages = await Message.findAll({
      where: whereClause,
      order: [['createdAt', 'ASC']],
      limit: 50
    });
    
    res.json({ 
      success: true, 
      data: messages,
      count: messages.length,
      timestamp: Date.now()
    });
  } catch (error) {
    console.error('获取最新消息失败:', error);
    res.status(500).json({ error: '获取最新消息失败' });
  }
});

export default router;